package com.theme.passport.controller.app;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.theme.common.mvc.utils.PageUtils;
import com.theme.common.mvc.validator.ValidatorUtils;
import com.theme.common.mvc.view.R;
import com.theme.passport.annotation.Login;
import com.theme.passport.controller.app.utils.AppContextUtil;
import com.theme.passport.entity.SysUserEntity;
import com.theme.passport.entity.UserEntity;
import com.theme.passport.entity.constant.DownloadTypeEnum;
import com.theme.passport.entity.constant.WidgeSizeEnum;
import com.theme.passport.entity.params.WidgePreviews;
import com.theme.passport.entity.theme.DownloadHistoryEntity;
import com.theme.passport.entity.theme.ThemeEntity;
import com.theme.passport.entity.theme.WallpaperEntity;
import com.theme.passport.entity.theme.WidgeEntity;
import com.theme.passport.form.DownloadBrowseLikeBuyForm;
import com.theme.passport.service.SysUserService;
import com.theme.passport.service.theme.DownloadHistoryService;
import com.theme.passport.service.theme.ThemeService;
import com.theme.passport.service.theme.WallpaperService;
import com.theme.passport.service.theme.WidgeService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.*;


@RestController
@RequestMapping("app/download")
@Api("用户主题下载记录")
public class DownloadHistoryController {

    @Autowired
    private SysUserService sysUserService;

    @Autowired
    private DownloadHistoryService downloadHistoryService;

    @Autowired
    private WallpaperService wallpaperService;

    @Autowired
    private ThemeService themeService;

    @Autowired
    private WidgeService widgeService;

    @Login
    @GetMapping("/list")
    @ApiOperation("查询用户下载记录接口")
    public R list(@RequestParam Map<String, Object> params){
        UserEntity currentUser = AppContextUtil.getCurrentUser();
        params.put("userId",currentUser.getId() +"");
        PageUtils page = downloadHistoryService.queryPage(params);
        return R.ok().put("page", page);
    }

    @Login
    @GetMapping("/widge-list")
    @ApiOperation("查询用户组件下载记录接口")
    public R widgeList(@RequestParam Map<String, Object> params){

        UserEntity currentUser = AppContextUtil.getCurrentUser();
        params.put("userId",currentUser.getId() +"");
        params.put("type",DownloadTypeEnum.WIDGE.getValue() +"");
        PageUtils page = downloadHistoryService.queryPage(params);
        List<DownloadHistoryEntity> downloadList = (List<DownloadHistoryEntity>) page.getList();
        if (downloadList == null || downloadList.size() <= 0){
            return R.ok().put("page", page);
        }
        List<Long> ids = new ArrayList<>();
        downloadList.forEach(downloadHistoryEntity -> {
            ids.add(downloadHistoryEntity.getObjectId());
        });
        params.put("ids", ids);
        List<WidgeEntity> list = widgeService.queryListBydistinctNameByIds(params);
        list.forEach(theme ->{
            //同名组件列表
            List<WidgeEntity> widgeSizeList = widgeService.queryWidgeListByName(theme.getName());
            if (widgeSizeList != null && widgeSizeList.size() >0){
                WidgeEntity widge = widgeSizeList.get(0);
                //SysUserEntity byId = sysUserService.getById(widge.getUserId());
                //widge.setUseNickname(byId.getNickname());
                BeanUtils.copyProperties(widge,theme);
                // 同名组件大小
                WidgePreviews widgePreviews = new WidgePreviews();
                widgeSizeList.forEach(item ->{
                    String widgetSize = item.getWidgetSize();
                    if (widgetSize.equals(WidgeSizeEnum.SMALL.getValue())){
                        widgePreviews.setSmall(item.getPreview());
                    }
                    if (widgetSize.equals(WidgeSizeEnum.MEDIUM.getValue())){
                        widgePreviews.setMidium(item.getPreview());
                    }
                    if (widgetSize.equals(WidgeSizeEnum.LAREGE.getValue())){
                        widgePreviews.setLarge(item.getPreview());
                    }
                });
                theme.setWidgePreviews(widgePreviews);
                theme.setWidgeSizeList(widgeSizeList);
            }
        });
        page.setList(list);
        return R.ok().put("page", page);
    }


    @Login
    @GetMapping("/widge-list/v2")
    @ApiOperation("查询用户组件下载记录接口v2")
    public R widgeListV2(@RequestParam Map<String, Object> params){

        UserEntity currentUser = AppContextUtil.getCurrentUser();
        params.put("userId",currentUser.getId() +"");
        params.put("type",DownloadTypeEnum.WIDGE.getValue() +"");
        PageUtils page = downloadHistoryService.queryPage(params);
        List<DownloadHistoryEntity> downloadList = (List<DownloadHistoryEntity>) page.getList();
        if (downloadList == null || downloadList.size() <= 0){
            return R.ok().put("page", page);
        }
        List<Long> ids = new ArrayList<>();
        downloadList.forEach(downloadHistoryEntity -> {
           ids.add(downloadHistoryEntity.getObjectId());
        });
        params.put("ids", ids);
        List<WidgeEntity> list = widgeService.queryListBydistinctNameByIds(params);
        List<WidgeEntity> chilendList = new ArrayList<>();
        for (WidgeEntity theme : list) {
            List<WidgeEntity> widgeSizeList = widgeService.queryWidgeListByName(theme.getName());
            chilendList.addAll(widgeSizeList);
        }
        for (WidgeEntity theme : list) {
            // 同名组件大小
            WidgePreviews widgePreviews = new WidgePreviews();
            for (WidgeEntity citem : chilendList) {
                if (theme.getName().equals(citem.getName())) {
                    String widgetSize = citem.getWidgetSize();
                    if (widgetSize.equals(WidgeSizeEnum.SMALL.getValue())) {
                        widgePreviews.setSmall(citem.getPreview());
                    }
                    if (widgetSize.equals(WidgeSizeEnum.MEDIUM.getValue())) {
                        widgePreviews.setMidium(citem.getPreview());
                    }
                    if (widgetSize.equals(WidgeSizeEnum.LAREGE.getValue())) {
                        widgePreviews.setLarge(citem.getPreview());
                    }
                    BeanUtils.copyProperties(citem, theme);
                }
            }
            theme.setWidgePreviews(widgePreviews);
        }
        List<WidgeEntity> returnList = new ArrayList<>();
        for (WidgeEntity item : list) {
            for (WidgeEntity citem : chilendList) {
                if (item.getName().equals(citem.getName())) {
                    WidgeEntity entity = new WidgeEntity();
                    BeanUtils.copyProperties(item, entity);
                    List<WidgeEntity> tempList = new ArrayList<>();
                    tempList.add(citem);
                    entity.setWidgeSizeList(tempList);
                    entity.setWidgetSize(tempList.get(0).getWidgetSize());
                    returnList.add(entity);
                }
            }
        }
        page.setList(returnList);
        return R.ok().put("page", page);
    }

    @Login
    @PostMapping("/add")
    @ApiOperation("添加用户下载记录的接口")
    public R add(@RequestBody DownloadBrowseLikeBuyForm form){
        //表单校验
        ValidatorUtils.validateEntity(form);

        DownloadHistoryEntity downloadHistory = new DownloadHistoryEntity();
        UserEntity currentUser = AppContextUtil.getCurrentUser();
        downloadHistory.setType(form.getType());
        downloadHistory.setObjectId(form.getObjectId());
        downloadHistory.setUserId(currentUser.getId());
        downloadHistory.setCreated(new Date());

        QueryWrapper<DownloadHistoryEntity> orderWrapper = new QueryWrapper<>();
        orderWrapper.and(wrapper -> wrapper
                .eq("user_id", currentUser.getId())
                .eq("type", downloadHistory.getType())
                .eq("object_id", downloadHistory.getObjectId()));
        List<DownloadHistoryEntity> list = downloadHistoryService.list(orderWrapper);
        if (list != null && list.size() > 0){
            return R.ok();
        }
        if (downloadHistory.getType() == DownloadTypeEnum.THEME.getValue()){
            ThemeEntity theme = themeService.getById(downloadHistory.getObjectId());
            if (theme != null){
                downloadHistory.setObjectName(theme.getName());
                downloadHistory.setImage(theme.getThumb());
            }
        }else if (downloadHistory.getType() == DownloadTypeEnum.WIDGE.getValue()){
            WidgeEntity widge = widgeService.getById(downloadHistory.getObjectId());
            if (widge != null){
                downloadHistory.setObjectName(widge.getName());
                downloadHistory.setImage(widge.getPreview());
            }
        }else {
            WallpaperEntity wallpaper = wallpaperService.getById(downloadHistory.getObjectId());
            if (wallpaper != null){
                downloadHistory.setObjectName(wallpaper.getName());
                downloadHistory.setImage(wallpaper.getImage());
            }
        }
        downloadHistoryService.save(downloadHistory);
        return R.ok();
    }

    @Login
    @PostMapping("/delete")
    @ApiOperation("删除用户下载记录接口 id数组")
    public R delete(@RequestBody Long[] ids){
        UserEntity currentUser = AppContextUtil.getCurrentUser();
        for(Long id : ids){
            downloadHistoryService.remove(new LambdaQueryWrapper<DownloadHistoryEntity>()
                    .eq(DownloadHistoryEntity::getUserId,currentUser.getId())
                    .eq(DownloadHistoryEntity::getObjectId,id));
        }
        return R.ok();
    }

}
